package com.sysadmin.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.common.base.BaseService;
import com.common.jdbc.DB4MapUtil;
import com.common.jdbc.DB4ObjUtil;
import com.common.jdbc.DBBaseUtil;
import com.common.jdbc.DBSource;
import com.common.pager.PageHelper;
import com.common.util.StringUtil;
import com.sysadmin.vo.JtreeVO;
import com.sysadmin.vo.MenusVO;
import com.sysadmin.vo.UsersVO;

public class MenuService extends BaseService {

	
	public List find(String pid,MenusVO vo,PageHelper pager){
		StringBuilder sql = new StringBuilder("select * from FXXT_SYS_MENU t  where 1=1 and t.DEL_FLAG='0' and t.PID=? ");
		if(vo!=null){
			if(!StringUtil.isBlank(vo.getMenuName())){
				sql.append(" and t.MENU_NAME like '%"+vo.getMenuName()+"%'");
			}
			
		}
		sql.append(" order by t.SORT_KEY");
		List<MenusVO> list = DB4ObjUtil.executePager4Obj(new MenusVO(), sql.toString(),pager,pid);
		
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public Map findMap(){
		Map menuMap = new HashMap();
		String sql = "select * from FXXT_SYS_MENU where 1=1 and DEL_FLAG='0' ";
		List<MenusVO> list = DB4ObjUtil.execute4Obj(new MenusVO(), sql);
		for(int i=0;i<list.size();i++){
			menuMap.put(list.get(i).getId(), list.get(i).getMenuName());
		}
		menuMap.put("0", "顶级");
		return menuMap;
	}
	
	public MenusVO get(String id){
		String sql = "select * from FXXT_SYS_MENU where 1=1 and ID=?";
		List<MenusVO> list = DB4ObjUtil.execute4Obj(new MenusVO(), sql, id);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}
	
	public String getMenuTree(String roleId){
		Document doc = DocumentHelper.createDocument();
		Element tree = doc.addElement("item");
		tree.addAttribute("id","0");
		Connection conn = DBSource.getConnection();
		List<String> menusIds =  findMenus(roleId);
		setTreeNode(conn,tree,"0",menusIds);
		try {
			conn.close();
		} catch (SQLException e) {
			log.info(e.getMessage(),e);
		}
		return doc.asXML();
	}
	
	
		
	
	private List<String> findMenus(String roleId){
		String menuSql = "select MENU_ID from FXXT_SYS_ROLETOMENU where 1=1 and ROLE_ID=?";
		Vector<Hashtable> menusList = DB4MapUtil.execute4Map(menuSql,roleId);
		List<String> menuIdsList = new ArrayList<String>();
		
		for (int i = 0; i < menusList.size(); i++) {
			String ids = (String) menusList.get(i).get("MENU_ID");
			menuIdsList.add(ids);
			}
		return menuIdsList;
	}
		
	
	public void setTreeNode(Connection conn,Element tree,String pid,List<String> menusIds){
		List<MenusVO> list = findMenuByPid(pid,conn);
	
		for (int i = 0; i < list.size(); i++) {
			MenusVO vo = list.get(i);
			Element e = tree.addElement("item");
			e.addAttribute("id", vo.getId());
			e.addAttribute("text", vo.getMenuName());
			e.addAttribute("open", "1");
			if(menusIds.contains(vo.getId())){
				e.addAttribute("checked", "1");
			}
			
			
			setTreeNode(conn,e,vo.getId(),menusIds);
		}
	}
	
	public String getMenuTree4User(UsersVO users){
		Document doc = DocumentHelper.createDocument();
		Element tree = doc.addElement("item");
		tree.addAttribute("id","0");
		Element e = tree.addElement("item");
		e.addAttribute("id", "-1");
		e.addAttribute("text", "景区客源智能分析系统");
		e.addAttribute("im0", "base.gif");
		e.addAttribute("im1", "base.gif");
		e.addAttribute("im2", "base.gif");
		e.addAttribute("open", "1");
		Connection conn = DBSource.getConnection();
		List<String> menusIds =  findMenus(users.getRoleId());
		setTreeNode4Users(conn,e,"0",menusIds,users);
		try {
			conn.close();
		} catch (SQLException e1) {
			log.info(e1.getMessage(),e1);
		}
		return doc.asXML();
	}
	
	public void setTreeNode4Users(Connection conn,Element tree,String pid,List<String> menusIds,UsersVO users){
		List<MenusVO> list = findMenuByPid(pid,conn);
		for (int i = 0; i < list.size(); i++) {
			MenusVO vo = list.get(i);
			if(menusIds.contains(vo.getId())||"admin".equals(users.getUsername())){
				Element e = tree.addElement("item");
				e.addAttribute("id", vo.getId());
				e.addAttribute("text", vo.getMenuName());
				e.addAttribute("open", "1");
				if(vo.getActionUrl()!=null&&!"".equals(vo.getActionUrl())){
					Element userData = e.addElement("userdata");
					userData.addAttribute("name","actionUrl");
					userData.setText(vo.getActionUrl());
				}
				setTreeNode4Users(conn,e,vo.getId(),menusIds,users);
			}
		}
	}
	
	
	public String getMenuObject4User(UsersVO users,HttpServletRequest req){
		JtreeVO jtree = new JtreeVO();
		jtree.setName("景区客源智能分析系统");
		jtree.setOpen(true);
		
		
		
		Connection conn = DBSource.getConnection();
		List<String> menusIds =  findMenus(users.getRoleId());
		setTreeObject4Users(conn,jtree,"0",menusIds,users,req);
		
		try {
			conn.close();
		} catch (SQLException e1) {
			log.info(e1.getMessage(),e1);
		}
		
		
		
		return jtree.toJsonString();
	}
	
	public void setTreeObject4Users(Connection conn,JtreeVO tree,String pid,List<String> menusIds,UsersVO users,HttpServletRequest req){
		List<MenusVO> list = findMenuByPid(pid,conn);
		if("0".equals(pid)){
			if(list.size()>0){
				tree.setIconSkin("pIcon01");
			}
		}
		List<JtreeVO> treeList = new ArrayList<JtreeVO>();
		
		for (int i = 0; i < list.size(); i++) {
			MenusVO vo = list.get(i);
			if(menusIds.contains(vo.getId())||"admin".equals(users.getUsername())){
				JtreeVO e = new JtreeVO();
				e.setName(vo.getMenuName());
				e.setOpen(true);
				if(!StringUtil.isBlank(vo.getActionUrl())){
				e.setUrl(req.getContextPath()+vo.getActionUrl());
				e.setTarget("main_right");
				}
				setTreeObject4Users(conn,e,vo.getId(),menusIds,users,req);
				treeList.add(e);
			}
		}
		tree.setChildren(treeList);
	}
	public List<MenusVO> findMenuByPid(String pid,Connection conn){
		String sql = "select * from FXXT_SYS_MENU where 1=1 and pid=? order by SORT_KEY";
		List<MenusVO> list = DB4ObjUtil.execute4ObjByConn(conn,new MenusVO(), sql,pid);
		
		return list;
	}
	
	

	public String isApply(String name,String id){
		String sql = "select * from FXXT_SYS_MENU where 1=1 and MENU_NAME=? and ID<>?";
		List<MenusVO> list = DB4ObjUtil.execute4Obj(new MenusVO(), sql, name,id);
		if(list.size()>0){
			return "1";
		}
		return "0";
	}
	
	public String isApply(MenusVO vo){
		String sql = "select * from FXXT_SYS_MENU where 1=1 and MENU_NAME=? and ID<>?";
		List<MenusVO> list = DB4ObjUtil.execute4Obj(new MenusVO(), sql, vo.getMenuName(),vo.getId());
		if(list.size()>0){
			return "1";
		}
		return "0";
	}
	
	public void delete(String ids){
		String sql = "update FXXT_SYS_MENU set DEL_FLAG='1' where id=?";
		if(!StringUtil.isBlank(ids)){
			String[] idArr = ids.split(",");
			DBBaseUtil.executeBatchUpdate(sql, idArr);
			
		}
	}
	
	public void delete(String[] ids){
		String sql = "update FXXT_SYS_MENU set DEL_FLAG='1' where id=?";
		if(!StringUtil.isBlank(ids)){
			DBBaseUtil.executeBatchUpdate(sql, ids);
			
		}
		
	}
	public String save(MenusVO vo){
		if(vo!=null){
			String isHave = isApply(vo);
			if("0".equals(isHave)){
				if(StringUtil.isBlank(vo.getId())){
						String id = StringUtil.getUuid();
						String sql = "insert into FXXT_SYS_MENU(ID,PID,MENU_CODE,MENU_NAME,SORT_KEY,IS_LEAF,ACTION_URL,RANK,DEL_FLAG) values(?,?,?,?,?,?,?,?,?)";
						DBBaseUtil.executeUpdate(sql, id,vo.getPid(),getCode(vo.getPid()),vo.getMenuName(),vo.getSortKey(),vo.getIsLeaf(),vo.getActionUrl(),vo.getRank(),"0");
				}else{
					
					String sql = "update FXXT_SYS_MENU set MENU_NAME=?,SORT_KEY=?,ACTION_URL=? where id=?";
					DBBaseUtil.executeUpdate(sql,vo.getMenuName(),vo.getSortKey(),vo.getActionUrl(), vo.getId());
				}
			}else{
				return "0";
			}
		}
		return "1";
	}
	public String getCode(String pid){
		String sql = "select max(MENU_CODE) from FXXT_SYS_MENU where 1=1 and PID=? ";
		String obj = (String) DB4ObjUtil.getObjectSingle(sql, pid);
		String newCode="001";
		if(!StringUtil.isBlank(obj)){
			int code = StringUtil.Str2Int(obj);
			 newCode = StringUtil.keeperStr(String.valueOf(code+1), obj.length(), "0");
			
		}else{
			MenusVO v = get(pid);
			if(v!=null){
				newCode = v.getMenuCode()+"001";
			}
		}
		log.info("maxcode===="+newCode);
		return newCode;
	}
	public List<MenusVO> find(){
		String sql = "select * from FXXT_SYS_MENU where 1=1 ";
		List<MenusVO> list = DB4ObjUtil.execute4Obj(new MenusVO(), sql);
		
		return list;
	}
	

	

	
}
